package com.ainge.easystudy.timeoutcenter;

import java.util.List;
import java.util.Set;

/**
 * 超时中心
 *
 * @author: Ainge
 * @Time: 2021/8/4 23:27
 */
public class TimeOutCenter {

    /**
     * 缓存key前缀
     */
    public static final String keyPrefix = "toc_";


    /**
     * 添加超时任务
     *
     * @param key         redis缓存key
     * @param timeOutTask 超时执行
     */
    public static void addTimeOutTask(String key, TimeOutTask timeOutTask) {
        if (timeOutTask == null) {
            throw new IllegalArgumentException("timeOutTask");
        }
        Long result = RedisClient.zadd(getKey(key), timeOutTask.getActionTime(), timeOutTask);
        System.out.println(String.format("addTimeOutTask success,result:%s", result));
    }

    /**
     * 获取可以执行的任务
     * @param key
     * @return
     */
    public static List<TimeOutTask> getActionTask(String key){
        return RedisClient.zrangeByScore(getKey(key), 0, System.currentTimeMillis(),TimeOutTask.class);
    }

    public static void deleteTask(String key,TimeOutTask timeOutTask){
        if(timeOutTask != null){
            RedisClient.zrem(getKey(key),timeOutTask);
        }
    }

    private static String getKey(String key) {
        return keyPrefix + key;
    }

}
